package com.qingxin.sys.action;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.qingxin.sys.utils.QRCoder;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.sys.verifier.Form;
import com.qingxin.sys.verifier.FormFactory;
import com.qingxin.sys.verifier.RegExps;

/**
 * 用于获取配置信息
 * @author Administrator
 *
 */
@Controller
public class ConfigAction {

	@Autowired
	private Producer captchaProducer;
	
	/**
	 * 获取表单验证配置
	 * @param action
	 * @param type
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/public/getFormVerifier.json", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object getFormVerifier(String action, String type, HttpServletRequest request){
		Map<String, Object> rsmap = new HashMap<String, Object>();
		//用于获取预定义的正则表达式
		if("getregexps".equalsIgnoreCase(type)){
			rsmap.put("regs", RegExps.getRegexpMap());
			rsmap.put("errs", RegExps.getRegexpErrorMap());
			return rsmap;
		}
		
		//获取验证规则
		if(StringUtils.isNotEmpty(action)){
			Form form = FormFactory.getForm(action);
			if(form != null){
				Map<String, Object> formcfg = form.getFormCfg();
				if(formcfg != null){
					rsmap.putAll(formcfg);
				}
			}
		}
		
		return rsmap;
	}
	
	
	
	/**
	 * 
	 * @param text 内容
	 * @param size 尺寸，默认200
	 * @param margin 边缘，默认4
	 * @param errorCorrect 容错级别，默认M（LMQH）
	 * @param fgcolor 前景色，默认黑色
	 * @param bgcolor 背景色，默认白色
	 * @param imgtype 图片类型，JPEG、PNG，默认PNG
	 * @param filename 下载图片的名称
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/public/qrcode.do", method=RequestMethod.GET)
	public String qrcode(String text, Integer size, Integer margin, String errorCorrect,
			String fgcolor, String bgcolor, String imgtype, String filename, HttpServletResponse response) throws Exception {
		if(StringUtils.isEmpty(text)){
			text = "QX";
		}
		if(size == null || size <= 0){
			size = 200;
		}
		String ext = null;
		if("jpg".equalsIgnoreCase(imgtype) || "jpeg".equalsIgnoreCase(imgtype)){
			imgtype = "JPEG";
			ext = "jpg";
		}else {
			imgtype = "PNG";
			ext = "png";
		}
		
		response.resetBuffer();
		response.setHeader("Pragma","no-cache");//禁止缓存
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/"+imgtype);
		if(StringUtils.isNotEmpty(filename)){
			try {
				filename = new String(filename.getBytes("gbk"), "iso8859-1");
				response.setHeader("Content-Disposition", "attachment; filename=" + filename+"."+ext);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
		if(margin == null || margin <= 0){
			margin = 4;
		}
		if(errorCorrect == null || errorCorrect.length()!=1 || "LMQH".indexOf(errorCorrect) == -1){
			errorCorrect = "M";
		}
		Color fgColor = Color.black;
		Color bgColor = Color.white;
		if(StringUtils.isNotEmpty(fgcolor)){
			if(fgcolor.length() == 6){
				fgColor = new Color(Integer.parseInt(fgcolor, 16));
			}else if(fgcolor.length() == 8){
				fgColor = new Color(Integer.parseInt(fgcolor, 16), true);
			}
		}
		if(StringUtils.isNotEmpty(bgcolor)){
			if(bgcolor.length() == 6){
				bgColor = new Color(Integer.parseInt(bgcolor, 16));
			}else if(bgcolor.length() == 8){
				bgColor = new Color(Integer.parseInt(bgcolor, 16), true);
			}
		}
		BufferedImage image = QRCoder.encode(text, size, size, margin, errorCorrect.charAt(0), fgColor, bgColor);
		
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, imgtype, out);
		out.flush();
		out.close();
		
		return null;
	}
	
	
	@RequestMapping(value="/public/kaptcha.do", method=RequestMethod.GET)
	public void kaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.resetBuffer();
		response.setHeader("Pragma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/png");
		
		String captchaText = captchaProducer.createText();
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaText);
		
		BufferedImage captchaImage = captchaProducer.createImage(captchaText);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(captchaImage, "PNG", out);
		
	}
	
	
}
